package com.qinghuan.hutubiji.util;

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    static long millisecondOfOneDay = 1000*60*60*24;

    public static java.sql.Date util2sql(java.util.Date date) {
        return new java.sql.Date(date.getTime());
    }

    /**
     * 获取今天，并且把时，分，秒和毫秒都置0， 因为通过日期控件获取到的日期，就是
     * 没有分秒和毫秒的
     * @return
     */
    public static Date today() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     *获取月初。使用Calendar获取本月第一天。
     * 在统计消费一览信息的时候，查看本月的消费数据，其实就是从数据库中把本月第一天到最后
     * 一天的数据查出来，再进行简单统计，所以需要一个获取本月第一天的方法
     * @return
     */
    public static Date monthBegin() {
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(new Date());
       calendar.set(Calendar.DATE, 1);
       calendar.set(Calendar.HOUR_OF_DAY, 0);
       calendar.set(Calendar.MINUTE, 0);
       calendar.set(Calendar.SECOND, 0);
       calendar.set(Calendar.MILLISECOND, 0);

       return calendar.getTime();
    }

    /**
     * 获取月末
     * @return
     */
    public static Date monthEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        calendar.set(Calendar.DATE, 1);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DATE, -1);

        return calendar.getTime();
    }

    /**
     * 获取本月一共有多少天
     * @return
     */
    public static int thisMonthTotalDay() {
        long lastDayMillSeconds = monthEnd().getTime();
        long firstDayMillSeconds = monthBegin().getTime();

        return (int)((lastDayMillSeconds -
                firstDayMillSeconds) / millisecondOfOneDay) + 1;
    }

    public static int thisMonthLeftDay() {
        long lastDayMilliSeconds = monthEnd().getTime();
        long todayMilliSeconds = today().getTime();

        return (int)((lastDayMilliSeconds -
                todayMilliSeconds) / millisecondOfOneDay) + 1;
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.monthBegin());
    }

}
